#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var connection;
var http = require('http');
var 	mysql  = require('mysql');
var sqlcn = mysql.createConnection({
	host     : 'localhost',
	user     : 'flash',
	password : 'flash',
	database : 'iw',
});

var server = http.createServer(function(request, response) {
    console.log('- Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(44, function() {
    console.log('- Server is listening on port 44');		

});

wsServer = new WebSocketServer({
    httpServer: server,
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  return true;
}
function login(input){
	var msg = {
		flag: "false"
	};
 	sqlcn.query("SELECT * FROM twalk_user WHERE username ='"+ input.username +"' AND password ='"+input.password+"'", function(err, rows, fields) {
		if(rows.length>0){
			rows[0].flag="login";
			connection.sendUTF(JSON.stringify(rows[0]));
		}else{				connection.sendUTF(JSON.stringify(msg));
		}				
	}); 
}

wsServer.on('request', function(request) {
console.log('newre');
     if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log('- Connection from origin ' + request.origin + ' rejected.');
      return;
    }

    connection = request.accept('iw-protocol', request.origin);
    console.log('- Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {	
			console.log(message.utf8Data);		
			var dataPack = JSON.parse(message.utf8Data);
			switch (dataPack.action){
				case "login":
					login(dataPack);					
					break;
			}
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log('- Peer ' + connection.remoteAddress + ' disconnected.');
    });
});